use crate::db::dao::im_collect_dao::{collect_inserts, collect_total, collect_updates, query_collect_by_key};
use crate::db::db::Db;
use crate::db::db_transaction::transaction;
use crate::db::pojo::pojo::{ImCollect};

pub struct ImCollectService;

impl ImCollectService {

    pub fn save_collects(&self, user_id: String, collects: &mut Vec<ImCollect>) {
        let db = Db::open();
        let user_id_clone = user_id.clone();
        transaction(db.clone(), move |db: Db| {
            self.save_collects_business(db, user_id_clone, collects)
        });
    }

    pub fn total(&self)->usize {
        let db = Db::open();
        let total = transaction(db.clone(), move |db: Db| {
            collect_total(db)
        });
        total
    }

    fn save_collects_business(&self, db: Db, user_id: String,  collects: &mut Vec<ImCollect>) {
        let mut insert_collects= Vec::new();
        let mut update_collects = Vec::new();

        for collect in collects {
            let db_collect = query_collect_by_key(db.clone(), &user_id, &collect.session_id, &collect.message_id);
            if db_collect.is_some() {
                collect.id = db_collect.unwrap().id.clone();
                update_collects.push(collect);
            } else {
                insert_collects.push(collect);
            }
        }

        collect_inserts(db.clone(), &mut insert_collects);
        collect_updates(db.clone(), &mut update_collects);
    }

}